﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.Instrufordelime;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.InstrufordelimeHarder
{
    public class AddInstrufordelimeHarder : IRequestHandler<AddInstrufordelimeCommand, APIResult<int>>
    {

        private readonly IMapper mapper;
        private IBaseRepository<Instrufordelime> repository;
        private readonly ILogger<AddInstrufordelimeHarder> logger;

        public AddInstrufordelimeHarder(IMapper mapper, IBaseRepository<Instrufordelime> repository, ILogger<AddInstrufordelimeHarder> logger)
        {
            this.mapper = mapper;
            this.repository = repository;
            this.logger = logger;
        }

        public async Task<APIResult<int>> Handle(AddInstrufordelimeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var model = repository.GetAll().Where(x => x.InstrufordelimeId > 0).Count();
                if (model==0)
                {
                    var xi = mapper.Map<Instrufordelime>(request);
                    xi.IsDeleted = false;
                    var a = repository.AddAsync(xi).Result;
                    result.Code = APIEnum.Success;
                    result.Msg = "添加成功";
                    result.Data = a;
                    logger.LogInformation("新增病案须知成功");
                }
                else
                {
                    request.InstrufordelimeId=1;
                    var xi = mapper.Map<Instrufordelime>(request);
         
                    xi.InstrufordelimeName = request.InstrufordelimeName;
                   await repository.Update(xi);
                    result.Code = APIEnum.Success;
                    result.Msg = "修改成功";
                    result.Data = 1;
                    logger.LogError("修改病案须知失败");

                }
              



              

                return await Task.FromResult(result);

            }
            catch (Exception ex)
            {
                logger.LogError("新增病案须知异常");
                throw;
            }
        }
    }
}
